<?php

namespace app\api\model;

use app\common\model\BaseModel;
use think\facade\Db;


class VipCard extends BaseModel
{


    protected $type = [1 => '天卡', 2 => '月卡', 3 => '季卡', 4 => '年卡'];
    protected $types = [1 => '天', 2 => '月', 3 => '季', 4 => '年'];
    // 表名
    protected $name = 'vip_card';

    public function getVipCard()
    {
        $list = self::where(['status' => 1])->order('sort asc')->select()->toArray();
        $data = [];
        foreach ($list as $val) {
            $val['price'] = "¥" . $val['price'] . '/' . $this->types[$val['type']];
            $data[$val['type']]['list'][] = $val;
            $data[$val['type']]['name'] = $this->type[$val['type']];
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }


    public function rechargeVipCard($requestData, $user)
    {
        $id = $requestData['id'] ?? 0;
        $vipCard = self::where(['id' => $id])->find();
        if ($vipCard['status'] == 0) {
            return ['status' => 0, 'message' => '会员卡已下架，请刷新后重试', 'result' => ''];
        }
        $res['out_trade_no'] = self::getOutTradeNo();
        $res['title'] = $vipCard['name'];
        $res['user_id'] = $user['id'];
        $res['vip_card_id'] = $id;
        $res['pay_money'] = $vipCard['price'];
        $res['create_time'] = time();
        $res['update_time'] = time();
        if (!Db::name('vip_card_order')->insert($res)) {
            return ['status' => 0, 'message' => '下单失败', 'result' => ''];
        }
        $result = (new SaveIng())->Pay($res, $user, 'rechargeVipCardNotify', '购买会员卡');
        if ($result) {
            return ['status' => 0, 'message' => '请求成功', 'result' => $result];
        } else {
            return ['status' => 0, 'message' => '下单失败', 'result' => ''];
        }
    }


    public static function getOutTradeNo()
    {
        $out_trade_no = sys_create_orderno(1);
        $order = Db::name('vip_card_order')->where('out_trade_no', $out_trade_no)->count();
        if ($order) {
            self::getOutTradeNo();
        }
        return $out_trade_no;
    }


}
